# -*- coding:utf-8 -*-
import json

import mitmproxy
from mitmproxy import http, ctx
from mitmproxy.tools._main import mitmdump


class Rewrite:
    def response(self, flow: mitmproxy.http.HTTPFlow):
        """
            The full HTTP response has been read.
            实现 rewrite
            1、修改股票名称
            2、修改股票价格
        """
        if "quote.json" in flow.request.pretty_url and "x=" in flow.request.pretty_url:
            # data=json.loads(flow.response.content)
            ctx.log.info(str(flow.response.content))
            data = json.loads(flow.response.content)
            # 把响应写入文件中进行修改
            with open('../data/data.json', "w", encoding='utf-8')as f:
                f.write(str(data))
            # 股价没有变化
            data['data']['items'][0]['quote']['name'] = "悟奕1"
            data['data']['items'][0]['quote']['current'] = '10'
            data['data']['items'][0]['quote']['percent'] = '0'
            # 股价上涨
            data['data']['items'][1]['quote']['name'] = "悟奕2"
            data['data']['items'][1]['quote']['current'] = '10'
            data['data']['items'][1]['quote']['percent'] = '0.1'
            # 股价下跌
            data['data']['items'][2]['quote']['name'] = "悟奕3"
            data['data']['items'][2]['quote']['current'] = '10'
            data['data']['items'][2]['quote']['percent'] = '-0.1'
            # 修改后的数据赋值给响应
            flow.response.text = json.dumps(data)
addons = [Rewrite()] # 实例化

# 方便断点调试
if __name__ == '__main__':
    mitmdump(['-s', __file__, '-p', "8082"])